package br.com.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import br.com.bean.AcessoBean;


public class LoginDao {

	/*public ArrayList<CadAcessoFuncionarioBean> getLogin(Connection conn, CadAcessoFuncionarioBean value) throws Exception{

		String sql = "SELECT * FROM cad_acesso_funcionario where cpf = ? and senha = ?;";

		PreparedStatement ps = conn.prepareStatement(sql);
		ps.setString(1, value.getCpf());
		ps.setString(2, value.getSenha());
		ResultSet rs = ps.executeQuery();
		ArrayList<CadAcessoFuncionarioBean> na = new ArrayList<CadAcessoFuncionarioBean>();
		while(rs.next()){
			CadAcessoFuncionarioBean a = new CadAcessoFuncionarioBean();
			a.setCpf(rs.getString("cpf"));
			a.setSenha(rs.getString("senha"));
			na.add(a);
		}
		return na;
	}

	public ArrayList<CadAcessoFuncionarioBean> getLogin(Connection conn) throws Exception{

		String sql = "SELECT cpf, senha FROM cad_acesso_funcionario ";

		PreparedStatement ps = conn.prepareStatement(sql);
		ResultSet rs = ps.executeQuery();
		ArrayList<CadAcessoFuncionarioBean> na = new ArrayList<CadAcessoFuncionarioBean>();
		while(rs.next()){
			CadAcessoFuncionarioBean a = new CadAcessoFuncionarioBean();
			a.setCpf(rs.getString("cpf"));
			a.setSenha(rs.getString("senha"));
			na.add(a);
		}
		return na;
	}*/

	public boolean validaLogin(Connection conn, String cpf, String senha) throws SQLException{
		PreparedStatement ps = null;
		ResultSet rs = null;
		String sql = "SELECT * FROM cad_acesso WHERE cpf = ? and senha = ?";
		try {
			ps = conn.prepareStatement(sql);
			ps.setString(1, cpf);
			ps.setString(2, senha);
			rs = ps.executeQuery();
			if(rs.next()){
				return true;
			}
		} finally {
			ps.close();
			rs.close();
		}
		return false;
	}

	public AcessoBean getSessao(Connection conn, AcessoBean value) throws Exception {
		//retorna dados para a sessao do usuario;
		String sql = "SELECT * FROM cad_acesso WHERE cpf = ? and senha = ?";

		PreparedStatement ps = conn.prepareStatement(sql);
		ps.setString(1, value.getCpf());
		ps.setString(2, value.getSenha());
		ResultSet rs = ps.executeQuery();
		AcessoBean a = null;
		if(rs.next()){	
			a = new AcessoBean();
			a.getNacesso().setId(rs.getInt("id_nivel_acesso"));
			a.setNome(rs.getString("nome"));
			a.setEmail(rs.getString("email"));
		}
		return a;
	}
	
	public int nivelAcesso (Connection conn, AcessoBean value) {
		try {
			int nivel = 0;
			String sql = "SELECT id_nivel_acesso FROM cad_acesso WHERE cpf = ? and senha = ?";
			PreparedStatement ps = conn.prepareStatement(sql);
			ps.setString(1, value.getCpf());
			ps.setString(2, value.getSenha());
			ResultSet rs = ps.executeQuery();
			while (rs.next()) {
			nivel = rs.getInt("id_nivel_acesso");
			}
			return nivel;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	
	
}
